<template>
  <div class="form-tag">
    <input :id="`form_${field.fieldName}`" :value="displayName" :placeholder="placeholder" :disabled="disabled" readonly @click="choose" />
    <button type="button" class="btn-text form-tag-clear" @click="clear" v-if="!isEmpty">
      <i class="iconfont icon-fe-close"></i>
    </button>
  </div>
</template>

<script>
/** mixin */
import FormMixin from '@src/component/form/mixin/form';

export default {
  name: 'FormTag',
  mixins: [FormMixin],
  props: {
    placeholder: {
      type: String,
      default: '',
    },
    value: [Object, Array],
  },
  data() {
    return {};
  },
  computed: {
    _multiple() {
      let { isMultiple } = this.field.setting || {};
      return isMultiple == 1;
    },
    _max() {
      return this._multiple ? -1 : 1;
    },
    isEmpty() {
      // 多选
      if (Array.isArray(this.value)) {
        return this.value.length <= 0;
      }

      let value = this.value || {};
      return !value.id;
    },
    displayName() {
      // 多选
      if (Array.isArray(this.value)) {
        return this.value.map(i => i.displayName || i.name).join(',');
      }

      let tag = this.value || {};
      return tag.displayName || tag.name;
    },
  },
  methods: {
    choose() {
      const option = {
        title: this.$t('common.placeholder.selectSomething', { 0: this.field.displayName }),
        max: this._max,
        isTag: true,
        showSp: true,
        selectedDepartments: this.value,
      };

      this.$fast.select.multi
        .department(option)
        .then(res => {
          if (res.status === 0) {
            const depts = res?.data?.depts || [];
            const value = this._multiple ? depts : depts[0];
            this.$emit('update', { newValue: value, field: this.field });
            this.$emit('input', value);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    clear() {
      let value = this._multiple ? [] : {};
      this.$emit('update', { newValue: value, field: this.field });
      this.$emit('input', value);
    },
  },
};
</script>

<style scoped lang="scss">
.form-tag {
  width: 100%;
  position: relative;

  input {
    padding-right: 32px;
    width: 100%;
    cursor: pointer;
  }

  &:hover .form-tag-clear {
    display: block;
  }
}

.form-tag-clear {
  position: absolute;
  top: 50%;
  right: 0;
  width: 32px;
  height: 32px;
  transform: translateY(-16px);
  padding: 0;
  margin: 0;
  color: #c0c4cc;

  display: none;

  i {
    font-size: 14px;
  }

  &:hover {
    color: #ed3f14;
  }
}
</style>
